var Fiber = require('fibers');
Fiber(function() {
	//初始化配置文件
	require("./initConfig")();

	var express = require('express');
	var app = express();

	//监听的端口
	app._port = 3000;

	// var domain = require("domain");
	// app.use(function(req, res, next) {
	// 	var dom = domain.create();
	// 	dom.on('error', next);
	// 	return dom.run(next);
	// });
	/* 会影响nginx的替换 */
	// //压缩 
	// var compression = require('compression')
	// app.use(compression());


	//json、urlencoded、multipart
	var bodyParser = require('body-parser');
	app.use(bodyParser.json());
	app.use(bodyParser.urlencoded({
		extended: true,
		limit: "50mb"
	}));
	// form-data
	var multipart = require('connect-multiparty');
	app.use(multipart());

	//RAW BODY
	app.use(function(req, res, next) {
		var data = '';
		var is_end;
		var fiber;
		req.setEncoding('utf8');
		req.on('data', function(chunk) {
			data += chunk;
		});
		req.on('end', function() {
			req.rawBody = data;
			is_end = true;
			fiber && fiber.run();
			req.emit("raw_body_parse_end");
		});
		req.__defineGetter__("rawBody", function() {
			if (!is_end) {
				fiber = Fiber.current;
				Fiber.yield();
			}
			return data;
		});
		next();
	});
	//Cookies
	var cookieParser = require('cookie-parser')
	app.use(cookieParser());

	//全局变量的初始化
	require("./appInit")(app);
	//设置运行的请求域
	app.use(require("./origin"));
	//API初始化路由
	require("./routerMap")(app);
	//系统事件注册
	require("./midInit")(app);

	var server = require('http').createServer(app).listen(app._port, function() {
		console.log("开始监听" + app._port + "端口");
	});
	app._server = server;
}).run();